//
// Created on 2023/4/12.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".

#include "demoClass.h"
#include <linux/nilfs2_api.h>

DemoClass::DemoClass() : env_(nullptr), wrapper_(nullptr) {}

DemoClass::~DemoClass() {
    napi_delete_reference(env_, wrapper_);
}

void DemoClass::Destructor(napi_env env, void *nativeObject, void* /*finalize_hint*/)
{
    reinterpret_cast<DemoClass *>(nativeObject)->~DemoClass();
}

napi_value DemoClass::Constructor(napi_env env, napi_callback_info info)
{
    napi_status status;
    size_t argc = 0;
    napi_value args[1] = {nullptr};
    napi_value jsThis;
    status = napi_get_cb_info(env, info, &argc, args, &jsThis, nullptr);
    if (status != napi_ok) {
        return nullptr;
    }
    
    DemoClass* obj = new DemoClass();
    
    obj->env_ = env;
    status = napi_wrap(env, jsThis, obj, DemoClass::Destructor, nullptr, &obj->wrapper_);
    if (status != napi_ok) {
        return nullptr;
    }
    return jsThis;
}

napi_value DemoClass::SayHello(napi_env env, napi_callback_info info){
    const char* str = "Hello from CPP world!";
    napi_value result; 
    napi_status status = napi_create_string_utf8(env, str, NAPI_AUTO_LENGTH, &result);
    if (status != napi_ok) {
        return nullptr;
    }
    return result;
}

void DemoClass::Init(napi_env env, napi_value exports)
{
    napi_status status;
    napi_property_descriptor descriptos[] = {
        {"sayHello", nullptr, SayHello, nullptr, nullptr, nullptr, napi_default, nullptr},
    };
    
    napi_value instance;
    status = napi_define_class(env, "DemoClass", NAPI_AUTO_LENGTH, Constructor, nullptr, sizeof(descriptos) / sizeof(*descriptos), descriptos, &instance);
    if (status != napi_ok) {
        return;
    }
    status = napi_set_named_property(env, exports, "DemoClass", instance);
    return;
}

